<?php


namespace app\api\controller;

use addons\third\model\Third;
use app\api\model\MeetConfigModel;
use app\api\model\MeetDepartmentModel;
use app\api\model\MeetModel;
use app\api\model\MeetTypeModel;

use app\api\model\MeetUserModel;
use app\api\service\Service;
use app\common\controller\Api;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use think\Db;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\TextCard;
use think\Exception;
use think\Session;


class Wechat extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['auth','loginUrl', 'test', 'ok'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    /*
    * 小春科技企业号（企业微信）
    *         wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0
   企业corpId:ww377c91a81493c595
   agentId : 1000011
   通讯录秘钥：wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0
   会议秘钥：zTaBypRVRipVmyqdquF_KH7f1PFGmqpu1aSH3dAQ4E0
   */
    protected static $config = [
        'corp_id' => 'ww377c91a81493c595',
        'secret' => 'zTaBypRVRipVmyqdquF_KH7f1PFGmqpu1aSH3dAQ4E0',
        'agent_id' => 100001,
        'suite_id' => 'ww377c91a81493c595',
        'suite_secret' => 'zTaBypRVRipVmyqdquF_KH7f1PFGmqpu1aSH3dAQ4E0',
        'token' => '应用的Token',
        'aes_key' => '应用的EncodingAESKey',
        'reg_template_id' => '注册定制化模板ID',
        'redirect_uri_install' => '安装应用的回调url（可选）',
        'redirect_uri_single' => '单点登录回调url （可选）',
        'redirect_uri_oauth' => '网页授权第三方回调url （可选）',
    ];

    protected $config_contacts = [
        'corp_id' => 'ww377c91a81493c595',
        'secret' => 'wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0', // 通讯录的 secret
    ];


    // 详情
    public function index2()
    {
        $app = Factory::officialAccount($this->config);
        $server = $app->server;
        $user = $app->user;

        $server->push(function ($message) use ($user) {
            $fromUser = $user->get($message['FromUserName']);

            return "{$fromUser->nickname} 您好！欢迎关注 overtrue!";
        });
        $server->serve()->send();
    }

    // 详情
    public function ok()
    {
        $user = $this->auth->getUserinfo();
        // print_r($user);
    }
    // 详情
    public function jump()
    {
        $jumpurl = "http://ww.baidu.com";
        header("Location: " . $jumpurl );
    }
    // 详情
    public function test()
    {
        $result = [
            'openid' => "HuFaXin",
            'userid' => "HuFaXin",
            'group_id' => 1,
            'department_id' =>1,
            'openname' => "HuFaXin",
            'nickname' => "HuFaXin",
            'avatar' => "HuFaXin",
            'mobile' => "15887869597",
            'biz_mail' => "332996896@qq.com",
            'access_token' => "dddddd",
            'refresh_token' => time() + 7200,
            'expires_in' => 7200,
            'logintime' => time(),
            'expiretime' => 7200,
        ];

        $loginret = Service::connect("workchat", $result);

        $user = $this->auth->getUser();
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success("登录成功", $data);
        echo $loginret;
    }
    // 登录
    public function auth()
    {
        $url = input('url');
        $app = Factory::work(self::$config);
        if (empty(input('code'))) {
            //Session::set('jumpurl', input('jumpurl') ? input('jumpurl') : "https://huiyi.bigchun.com/api/wechat/ok");
            $callbackUrl = 'https://huiyi.bigchun.com'; // 需设置可信域名
            if(!empty($url)){
                $callbackUrl= $url;
            }
// 返回一个 redirect 实例
            $redirect = $app->oauth->redirect($callbackUrl);
// 获取企业微信跳转目标地址
            $targetUrl = $redirect->getTargetUrl();
            log_print('XXXX'.$targetUrl);
            log_print($targetUrl);
// 直接跳转到企业微信授权
            $redirect->send();
        } else {
            $user = $app->oauth->detailed()->user();
// 获取用户信息
            $app->oauth->setRedirectUrl();
            $contacts = Factory::work($this->config_contacts);
            $info = $contacts->user->get($user->getId());
            log_print('auth授权');
            log_print($info);
            $result = [
                'openid' => $info['userid'],
                'userid' => $info['userid'],
                'group_id' => $info['department'][0],
                'department_id' =>implode(",",$info['department']) ,
                'openname' => $info['name'],
                'nickname' => $info['userid'],
                'avatar' => $info['avatar'],
                'mobile' => $info['mobile'],
                'biz_mail' => $info['biz_mail'],
                'access_token' => $user->getAccessToken(),
                'refresh_token' => time() + 7200,
                'expires_in' => 7200,
                'logintime' => time(),
                'expiretime' => 7200,
            ];
            log_print($result);
            if(empty($info['mobile'])){
                $info['mobile'] = $info['userid'];
            }
            //$loginret = Service::connect("workchat", $result);
            $user = \app\common\model\User::getByMobile($info['mobile']);
            if($user){
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            }else{
                $extend = [
                    'avatar' => $info['avatar'],
                    'wx_userid' => $info['userid'],
                    'group_id' => $result['group_id'],
                    'department_id' => $result['department_id'],
                ];

                $ret = $this->auth->register($info['name'], '', $info['biz_mail'], $info['mobile'], $extend);
                $user = $this->auth->getUserinfo();
                $time = time();
                $values = [
                    'user_id' => $user['id'],
                    'platform'      => 'workchat',
                    'group_id'        => $result['group_id'],
                    'openid'        => $result['openid'],
                    'openname'      => $result['nickname'],
                    'access_token'  => $result['access_token'],
                    'refresh_token' => $result['refresh_token'],
                    'expires_in'    => $result['expires_in'],
                    'logintime'     => $time,
                    'expiretime'    => $time + $result['expires_in'],
                ];
                $third = Third::create($values,true);
            }
            if ($ret) {
                $user = $this->auth->getUserinfo();
                //$jumpurl = Session::get('jumpurl');

                if ($url == '') {
                    $url = request()->domain();
                    header("Location: " . $url . "/?token=" . $user['token']);
                } else {
                    //if(empty($url)){
                        //$url = request()->domain().'/';

                    /*}else {
                        $url = request()->domain().'/#/pages/tabbar/tabbar-4/tabbar-4';
                    }*/
                    header("Location: " . $url . "?token=" . $user['token']);
                }
            }
        }

    }

    // 部门列表
    public function department()
    {

        if (Session::get('departmentData')) {
            $cacheData = Session::get('departmentData');
            // 判断缓存信息是否过期，如果过期删除缓存文件，并将data重置
            if (time() - $cacheData['timestamp']/1 >= 7200) {
                Session::clear('departmentData');
                Session::set('departmentData', null);
                $cacheData = array();
            }
        }

        $department = [];
        if (!Session::has('departmentData')) {
            $contacts = Factory::work($this->config_contacts);
            $data = $contacts->department->list();
            // 获取指定部门及其下的子部门
            //  $contacts->department->list($id);
            $department = $data['department'];
            foreach ($department as $k => $val) {
                $val['updatetime'] = time();
                $res = (new MeetDepartmentModel())->allowField(true)->save($val, ['id' => $val['id']]);
                if ($res == 0) {
                    (new MeetDepartmentModel($val))->allowField(true)->save();
                }
            }
            $cacheData = array(
                'list' => $department,
                'timestamp' =>  time()
            );
            Session::set('departmentData', $cacheData);
        }else{
            if (isset($cacheData['list'])) {
                $department = $cacheData['list'];
            }
        }
        $this->success("成功", $department);
    }

    // 人员列表
    public function users()
    {
        if (Session::get('departmentUserData')) {
            $cacheData = Session::get('departmentUserData');
            // 判断缓存信息是否过期，如果过期删除缓存文件，并将data重置
            if (time() - $cacheData['timestamp']/1 >= 7200) {
                Session::clear('departmentUserData');
                Session::set('departmentUserData', null);
                $cacheData = array();
            }
        }

        // Session::set('departmentUserData', null);
        $departmentUser = [];
        if (!Session::has('departmentUserData')) {
            $departmentId = 1;
            $contacts = Factory::work($this->config_contacts);
            // 递归获取子部门下面的成员
            $data = $contacts->user->getDetailedDepartmentUsers($departmentId, true);

            $departmentUser = $data['userlist'];
            foreach ($departmentUser as $k => $val) {
                $val['updatetime'] = time();
                $val['status'] = "normal";
                $val['username'] = $val['userid'];
                $val['avatar'] = $val['avatar'];
                $val['nickname'] = $val['name'];
                $val['group_id'] = $val['department'][0];
                $val['department_id'] = implode(",",$val['department']) ;
                $val['biz_mail'] = $val['email'];
                $res = (new MeetUserModel())->allowField(true)->save($val, ['mobile' => $val['mobile']]);
                if ($res == 0) {
                    (new MeetUserModel($val))->allowField(true)->save();
                }
            }
            $cacheData = array(
                'list' => $departmentUser,
                'timestamp' =>  time()
            );
            Session::set('departmentUserData', $cacheData);
        }else{
            if (isset($cacheData['list'])) {
                $departmentUser = $cacheData['list'];
            }
        }
        $this->success("成功", $departmentUser);

        //  $contacts->department->list($id);
        $this->success("成功", $data);
    }

    // token
    public function token()
    {
        log2txt($this->config);
        $app = Factory::openWork($this->config);
        $token = $app->suite_access_token->getToken();
        echo $token;
    }


    //
    public function tag()
    {
        $contacts = Factory::work($this->config_contacts);
        $tagId = 1;
        $contacts->tag->delete($tagId);
        $res =  $contacts->tag->create("room_manager", $tagId);
        /*
                $tagId = 2;
                $contacts->tag->delete($tagId);
                $res =  $contacts->tag->create("check_ids", $tagId);

                $tagId = 3;
                $contacts->tag->delete($tagId);
                $res =  $contacts->tag->create("attend_topic_ids", $tagId);

                $tagId = 4;
                $contacts->tag->delete($tagId);
                $res =  $contacts->tag->create("attend_meet_ids", $tagId);

                $tagId = 5;
                $contacts->tag->delete($tagId);
                $res =  $contacts->tag->create("issued_ids", $tagId);

                $tagId = 6;
                $contacts->tag->delete($tagId);
                $res =  $contacts->tag->create("approver_ids", $tagId);

        */
        // $res =  $contacts->tag->tagUsers($tagId, ["HuFaXin","HuFaXin"]);
        $this->success("发送成功", $res);

    }
    //
    public function taglist()
    {
        $contacts = Factory::work($this->config_contacts);
        $tagId = 11;
        $contacts->tag->delete($tagId);
        $res =  $contacts->tag->create("room_manager".time(), $tagId);

        $res =  $contacts->tag->list();
        $this->success("发送成功", $res);

    }


    //
    public function message()
    {
        $arr = [
            'title' => 'hoo1212你的请假单审批通过',
            'description' => '1212单号：1928373, ....',
            'url' => 'https://huiyi.bigchun.com/api/wechat/test'
        ];
        $toArr = ["HuFaXin"];
        //  $res =   $this->sendMessage($arr,$toArr);
        $toTagArr = [1];
        $res = $this->sendTagMessage($arr,$toTagArr);
        if ($res['errcode'] == 0) {
            $this->success("发送成功", $res);
        } else {
            $this->error("发送失败", $res);
        }
    }


    // 发送消息
    public static function sendMessage($arr = [],$toArr=[])
    {

        $config = MeetConfigModel::getMsgConfigByMeetId($arr['meet_id']);
        $corpid = $config['corpid'];
        $secret = $config['Secret'];
        $AgentId = $config['AgentId'];
        $config = [
            'corp_id' => $corpid,
            'secret' => $secret,
            'agent_id' => $AgentId,
        ];
        $app = Factory::work($config);
        $messenger = $app->messenger;
        $message = new TextCard($arr);
        try {
            $res = $messenger->message($message)->ofAgent($AgentId)->toUser($toArr)->send();;//$messenger->message('已经审批通过！')->ofAgent("1000011")->toUser('HuFaXin')->send();
            log_print('消息推送成功start');
            log_print($res);
            log_print('消息推送成功end');
            return $res;
        } catch (InvalidArgumentException $e) {
            log_print('消息推送失败start1');
            log_print($e->getMessage());
            log_print('消息推送失败end1');
            return $e ;
        } catch (RuntimeException $e) {
            log_print('消息推送失败start2');
            log_print($e->getMessage());
            log_print('消息推送失败end2');
            return $e ;
        }
    }

    // 发送消息
    public static function sendTagMessage($arr = [],$toArr=[])
    {
        $app = Factory::work(Wechat::$config);
        $messenger = $app->messenger;
        $message = new TextCard($arr);
        try {
            $res = $messenger->message($message)->ofAgent("1000011")->toTag($toArr)->send();;//$messenger->message('已经审批通过！')->ofAgent("1000011")->toUser('HuFaXin')->send();
            return $res;
        } catch (InvalidArgumentException $e) {
            return $e ;
        } catch (RuntimeException $e) {
            return $e ;
        }
    }

}
